#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
污染类型管理API接口
提供污染类型和样例的RESTful API
"""

from fastapi import APIRouter, Depends, HTTPException, Query, Request
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field
from models.pollution_type import PollutionType, PollutionTypeExample
from services.pollution_type_service import pollution_type_service
from core.auth import get_current_active_user
from models.user import User
from core.logging_config import get_logger
from core.database import get_db_session
import time

logger = get_logger("pollution_types_api")

router = APIRouter(tags=["pollution-types"])

class PollutionTypeCreate(BaseModel):
    """污染类型创建请求"""
    code: str = Field(..., min_length=1, max_length=20, description="污染类型代码")
    name: str = Field(..., min_length=1, max_length=100, description="污染类型名称")
    parent_code: Optional[str] = Field(None, max_length=20, description="父级类型代码")
    level: int = Field(1, ge=1, le=3, description="层级深度")
    tag_name: Optional[str] = Field(None, max_length=100, description="标签名称")
    tag_category: Optional[str] = Field(None, max_length=50, description="标签分类")
    usage_scope: Optional[str] = Field(None, description="使用范围")
    exclusion_scope: Optional[str] = Field(None, description="排除范围")
    display_name: Optional[str] = Field(None, max_length=100, description="显示名称")
    parent_tag_code: Optional[str] = Field(None, max_length=20, description="父级标签代码")
    sort_order: int = Field(0, ge=0, description="排序顺序")
    description: Optional[str] = Field(None, description="详细说明")
    customer_id: Optional[str] = Field("default", description="客户标识")

class PollutionTypeUpdate(BaseModel):
    """污染类型更新请求"""
    name: Optional[str] = Field(None, min_length=1, max_length=100, description="污染类型名称")
    parent_code: Optional[str] = Field(None, max_length=20, description="父级类型代码")
    level: Optional[int] = Field(None, ge=1, le=3, description="层级深度")
    tag_name: Optional[str] = Field(None, max_length=100, description="标签名称")
    tag_category: Optional[str] = Field(None, max_length=50, description="标签分类")
    usage_scope: Optional[str] = Field(None, description="使用范围")
    exclusion_scope: Optional[str] = Field(None, description="排除范围")
    display_name: Optional[str] = Field(None, max_length=100, description="显示名称")
    parent_tag_code: Optional[str] = Field(None, max_length=20, description="父级标签代码")
    sort_order: Optional[int] = Field(None, ge=0, description="排序顺序")
    description: Optional[str] = Field(None, description="详细说明")
    is_active: Optional[bool] = Field(None, description="是否激活")

@router.post("/", response_model=dict)
async def create_pollution_type(
    request: PollutionTypeCreate,
    current_user: User = Depends(get_current_active_user)
):
    """创建污染类型"""
    start_time = time.time()
    customer_id = request.customer_id or "default"

    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        # 移除customer_id字段，传递给服务层
        request_data = request.model_dump(exclude={"customer_id"})
        pollution_type = pollution_type_service.create_pollution_type(customer_id, request_data)

        logger.info(f"用户 {current_user.username} 创建污染类型: {pollution_type.get('name')} (客户: {customer_id})")

        # 服务层已返回字典数据，直接使用
        return {
            "code": 200,
            "message": "创建成功",
            "data": pollution_type,
            "timestamp": time.time()
        }
    except ValueError as e:
        logger.warning(f"创建污染类型失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"创建污染类型异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.get("/", response_model=dict)
async def get_pollution_types(
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    active_only: bool = Query(True, description="仅显示激活的类型"),
    tree_view: bool = Query(False, description="返回树形结构"),
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """获取污染类型列表"""
    try:
        logger.info(f"获取污染类型列表 - 用户: {getattr(current_user, 'username', 'unknown')}, 客户: {customer_id}")

        # 检查用户权限：超级用户可以访问所有数据，普通用户只能访问默认数据
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限访问指定客户数据")

        if tree_view:
            data = pollution_type_service.get_hierarchy_tree(customer_id)
        elif keyword:
            data = pollution_type_service.search_pollution_types(customer_id, keyword)
        else:
            data = pollution_type_service.get_all_pollution_types(customer_id, active_only)

        logger.info(f"用户 {current_user.username} 获取污染类型列表成功 (客户: {customer_id}, 数量: {len(data) if isinstance(data, list) else 0})")

        return {
            "code": 200,
            "message": "获取成功",
            "data": data,
            "count": len(data) if isinstance(data, list) else 0,
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"获取污染类型列表异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 导出接口 - 必须在 /{type_id} 之前定义以避免路由冲突
@router.get("/export")
async def export_pollution_types(
    customer_id: str = Query("default", description="客户标识"),
    format: str = Query("json", pattern="^(json|excel)$", description="导出格式"),
    current_user: User = Depends(get_current_active_user)
):
    """导出污染类型数据"""
    # 参数验证
    if format not in ["json", "excel"]:
        raise HTTPException(status_code=422, detail="无效的导出格式")

    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限访问指定客户数据")

        if format == "json":
            # 导出JSON格式
            types = pollution_type_service.get_all_pollution_types(customer_id, active_only=False)
            data = {
                "customer_id": customer_id,
                "export_time": time.time(),
                "total_count": len(types),
                "pollution_types": types
            }

            logger.info(f"用户 {current_user.username} 导出污染类型JSON数据 (客户: {customer_id}, 数量: {len(types)})")

            return {
                "code": 200,
                "message": "导出成功",
                "data": data,
                "timestamp": time.time()
            }
        else:
            # 导出Excel格式
            try:
                from services.pollution_type_import_export import PollutionTypeImportExport
                import os
                import tempfile
                import traceback

                exporter = PollutionTypeImportExport()

                # 创建临时文件路径
                tmp_path = tempfile.mktemp(suffix='.xlsx')

                try:
                    logger.info(f"开始导出Excel格式污染类型数据 - 客户: {customer_id}")
                    count = exporter.export_pollution_types_to_excel(tmp_path, customer_id)

                    # 读取文件内容并返回
                    with open(tmp_path, 'rb') as f:
                        file_content = f.read()

                    os.unlink(tmp_path)  # 删除临时文件

                    logger.info(f"用户 {current_user.username} 导出污染类型Excel数据成功 (客户: {customer_id}, 数量: {count})")

                    from fastapi.responses import Response
                    return Response(
                        content=file_content,
                        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        headers={"Content-Disposition": f"attachment; filename=pollution_types_{customer_id}_{int(time.time())}.xlsx"}
                    )
                except Exception as e:
                    if os.path.exists(tmp_path):
                        try:
                            os.unlink(tmp_path)
                        except:
                            pass
                    logger.error(f"Excel导出处理失败: {str(e)}")
                    logger.error(f"Excel导出异常堆栈: {traceback.format_exc()}")
                    raise e
            except ImportError as e:
                logger.error(f"Excel导出依赖导入失败: {str(e)}")
                raise HTTPException(status_code=500, detail="Excel导出功能不可用，请检查依赖")
            except Exception as e:
                logger.error(f"Excel导出功能异常: {str(e)}")
                logger.error(f"Excel导出异常堆栈: {traceback.format_exc()}")
                raise HTTPException(status_code=500, detail="Excel导出功能异常")
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"导出污染类型数据异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/{type_id}", response_model=dict)
async def get_pollution_type(
    type_id: int,
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """获取单个污染类型"""
    try:
        logger.info(f"开始获取污染类型 - ID: {type_id}, Customer: {customer_id}, User: {current_user.username}")

        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限访问指定客户数据")

        logger.info(f"调用服务层获取污染类型...")
        pollution_type = pollution_type_service.get_pollution_type(customer_id, type_id)
        logger.info(f"服务层返回结果: {pollution_type}")

        if not pollution_type:
            raise HTTPException(status_code=404, detail="污染类型不存在")

        logger.info(f"用户 {current_user.username} 获取污染类型: {pollution_type.get('name')} (客户: {customer_id})")

        # 服务层已返回字典数据，直接使用
        return {
            "code": 200,
            "message": "获取成功",
            "data": pollution_type,
            "timestamp": time.time()
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取污染类型异常: {str(e)}")
        logger.error(f"异常类型: {type(e)}")
        import traceback
        logger.error(f"异常堆栈: {traceback.format_exc()}")
        raise HTTPException(status_code=500, detail=f"服务器内部错误: {str(e)}")


@router.get("/debug/{type_id}", response_model=dict)
async def debug_get_pollution_type(
    type_id: int,
    customer_id: str = Query("default", description="客户标识")
):
    """调试端点：获取单个污染类型（无认证）"""
    try:
        logger.info(f"[DEBUG] 开始获取污染类型 - ID: {type_id}, Customer: {customer_id}")

        logger.info(f"[DEBUG] 调用服务层获取污染类型...")
        pollution_type = pollution_type_service.get_pollution_type(customer_id, type_id)
        logger.info(f"[DEBUG] 服务层返回结果: {pollution_type}")

        if not pollution_type:
            return {
                "code": 404,
                "message": "污染类型不存在",
                "data": None,
                "timestamp": time.time()
            }

        logger.info(f"[DEBUG] 成功获取污染类型: {pollution_type.get('name')}")

        return {
            "code": 200,
            "message": "获取成功",
            "data": pollution_type,
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"[DEBUG] 获取污染类型异常: {str(e)}")
        logger.error(f"[DEBUG] 异常类型: {type(e)}")
        import traceback
        logger.error(f"[DEBUG] 异常堆栈: {traceback.format_exc()}")
        return {
            "code": 500,
            "message": f"服务器内部错误: {str(e)}",
            "data": None,
            "timestamp": time.time()
        }

@router.put("/{type_id}", response_model=dict)
async def update_pollution_type(
    type_id: int,
    request: PollutionTypeUpdate,
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """更新污染类型"""
    # 参数验证
    if not isinstance(type_id, int) or type_id <= 0:
        raise HTTPException(status_code=422, detail="无效的类型ID")

    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        update_data = request.model_dump(exclude_unset=True)
        if not update_data:
            raise HTTPException(status_code=422, detail="没有提供更新数据")

        pollution_type = pollution_type_service.update_pollution_type(customer_id, type_id, update_data)
        if not pollution_type:
            raise HTTPException(status_code=404, detail="污染类型不存在")

        logger.info(f"用户 {current_user.username} 更新污染类型: {pollution_type.get('name')} (客户: {customer_id})")

        # 服务层已返回字典数据，直接使用
        return {
            "code": 200,
            "message": "更新成功",
            "data": pollution_type,
            "timestamp": time.time()
        }
    except ValueError as e:
        logger.warning(f"更新污染类型失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新污染类型异常: {str(e)}")
        import traceback
        logger.error(f"更新污染类型异常堆栈: {traceback.format_exc()}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.delete("/{type_id}", response_model=dict)
async def delete_pollution_type(
    type_id: int,
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """删除污染类型"""
    # 参数验证
    if not isinstance(type_id, int) or type_id <= 0:
        raise HTTPException(status_code=422, detail="无效的类型ID")

    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        success = pollution_type_service.delete_pollution_type(customer_id, type_id)
        if not success:
            raise HTTPException(status_code=404, detail="污染类型不存在")

        logger.info(f"用户 {current_user.username} 删除污染类型 ID: {type_id} (客户: {customer_id})")

        return {
            "code": 200,
            "message": "删除成功",
            "data": {"deleted": True, "type_id": type_id},
            "timestamp": time.time()
        }
    except ValueError as e:
        logger.warning(f"删除污染类型失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除污染类型异常: {str(e)}")
        import traceback
        logger.error(f"删除污染类型异常堆栈: {traceback.format_exc()}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

# 污染类型样例管理API
class PollutionTypeExampleCreate(BaseModel):
    """污染类型样例创建请求"""
    example_content: str = Field(..., min_length=1, description="样例内容")
    judgment_basis: Optional[str] = Field(None, description="判断依据")
    keywords: Optional[str] = Field(None, description="关键词（逗号分隔）")
    confidence_level: float = Field(0.8, ge=0.0, le=1.0, description="置信度")

class PollutionTypeExampleUpdate(BaseModel):
    """污染类型样例更新请求"""
    example_content: Optional[str] = Field(None, min_length=1, description="样例内容")
    judgment_basis: Optional[str] = Field(None, description="判断依据")
    keywords: Optional[str] = Field(None, description="关键词（逗号分隔）")
    confidence_level: Optional[float] = Field(None, ge=0.0, le=1.0, description="置信度")
    is_active: Optional[bool] = Field(None, description="是否激活")

@router.post("/{type_id}/examples", response_model=dict)
async def create_pollution_type_example(
    type_id: int,
    request: PollutionTypeExampleCreate,
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """创建污染类型样例"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        example = pollution_type_service.create_pollution_type_example(customer_id, type_id, request.model_dump())
        logger.info(f"用户 {current_user.username} 创建污染类型样例 (类型ID: {type_id}, 客户: {customer_id})")

        # 服务层已返回字典数据，直接使用
        return {
            "code": 200,
            "message": "创建成功",
            "data": example,
            "timestamp": time.time()
        }
    except ValueError as e:
        logger.warning(f"创建污染类型样例失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"创建污染类型样例异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.get("/{type_id}/examples", response_model=dict)
async def get_pollution_type_examples(
    type_id: int,
    active_only: bool = Query(True, description="仅显示激活的样例"),
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """获取污染类型样例列表"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限访问指定客户数据")

        examples = pollution_type_service.get_pollution_type_examples(customer_id, type_id, active_only)
        logger.info(f"用户 {current_user.username} 获取污染类型样例列表 (类型ID: {type_id}, 客户: {customer_id}, 数量: {len(examples)})")

        return {
            "code": 200,
            "message": "获取成功",
            "data": examples,
            "count": len(examples),
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"获取污染类型样例列表异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.put("/examples/{example_id}", response_model=dict)
async def update_pollution_type_example(
    example_id: int,
    request: PollutionTypeExampleUpdate,
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """更新污染类型样例"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        example = pollution_type_service.update_pollution_type_example(customer_id, example_id, request.model_dump(exclude_unset=True))
        if not example:
            raise HTTPException(status_code=404, detail="样例不存在")

        logger.info(f"用户 {current_user.username} 更新污染类型样例 ID: {example_id} (客户: {customer_id})")

        # 服务层已返回字典数据，直接使用
        return {
            "code": 200,
            "message": "更新成功",
            "data": example,
            "timestamp": time.time()
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新污染类型样例异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.delete("/examples/{example_id}", response_model=dict)
async def delete_pollution_type_example(
    example_id: int,
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """删除污染类型样例"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        success = pollution_type_service.delete_pollution_type_example(customer_id, example_id)
        if not success:
            raise HTTPException(status_code=404, detail="样例不存在")

        logger.info(f"用户 {current_user.username} 删除污染类型样例 ID: {example_id} (客户: {customer_id})")

        return {
            "code": 200,
            "message": "删除成功",
            "data": {"deleted": True, "example_id": example_id},
            "timestamp": time.time()
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除污染类型样例异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.post("/analyze", response_model=dict)
async def analyze_content_with_examples(
    content: str = Query(..., min_length=1, description="要分析的内容"),
    customer_id: str = Query("default", description="客户标识"),
    min_confidence: float = Query(0.1, ge=0.0, le=1.0, description="最小置信度阈值"),
    current_user: User = Depends(get_current_active_user)
):
    """使用样例分析内容"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限访问指定客户数据")

        results = pollution_type_service.analyze_content_with_examples(customer_id, content)

        # 过滤低置信度结果
        filtered_results = [r for r in results if r["confidence"] >= min_confidence]

        logger.info(f"用户 {current_user.username} 分析内容 (客户: {customer_id}, 结果数: {len(filtered_results)})")

        return {
            "code": 200,
            "message": "分析成功",
            "data": filtered_results,
            "total_results": len(results),
            "filtered_results": len(filtered_results),
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"内容分析异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.get("/examples/search", response_model=dict)
async def search_examples_by_keywords(
    keywords: str = Query(..., min_length=1, description="关键词，用逗号分隔"),
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """根据关键词搜索样例"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限访问指定客户数据")

        keyword_list = [k.strip() for k in keywords.split(",") if k.strip()]
        results = pollution_type_service.search_examples_by_keywords(customer_id, keyword_list)

        logger.info(f"用户 {current_user.username} 搜索样例 (客户: {customer_id}, 关键词: {keyword_list}, 结果数: {len(results)})")

        return {
            "code": 200,
            "message": "搜索成功",
            "data": results,
            "keyword_count": len(keyword_list),
            "result_count": len(results),
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"样例搜索异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 批量操作接口
class BatchPollutionTypeCreate(BaseModel):
    """批量创建污染类型请求"""
    types: List[Dict[str, Any]] = Field(..., min_items=1, max_items=100, description="污染类型列表")

@router.post("/batch", response_model=dict)
async def batch_create_pollution_types(
    request: BatchPollutionTypeCreate,
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建污染类型"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        created_types = []
        failed_items = []

        for i, type_data in enumerate(request.types):
            try:
                pollution_type = pollution_type_service.create_pollution_type(customer_id, type_data)
                # 在服务层会话内获取完整的字典数据
                from core.database import get_db_session
                with get_db_session() as db:
                    fresh_type = db.query(PollutionType).filter(PollutionType.id == pollution_type.id).first()
                    created_types.append(fresh_type.to_dict() if fresh_type else pollution_type.to_dict())
            except Exception as e:
                failed_items.append({
                    "index": i,
                    "data": type_data,
                    "error": str(e)
                })

        logger.info(f"用户 {current_user.username} 批量创建污染类型 (客户: {customer_id}, 成功: {len(created_types)}, 失败: {len(failed_items)})")

        return {
            "code": 200,
            "message": "批量创建完成",
            "data": {
                "created_count": len(created_types),
                "failed_count": len(failed_items),
                "created_types": created_types,
                "failed_items": failed_items
            },
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"批量创建污染类型异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


class BatchPollutionTypeExampleCreate(BaseModel):
    """批量创建污染类型样例请求"""
    examples: List[Dict[str, Any]] = Field(..., min_items=1, max_items=100, description="样例列表")

@router.post("/examples/batch", response_model=dict)
async def batch_create_pollution_type_examples(
    request: BatchPollutionTypeExampleCreate,
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建污染类型样例"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        created_examples = []
        failed_items = []

        for i, example_data in enumerate(request.examples):
            try:
                pollution_type_id = example_data.get("pollution_type_id")
                if not pollution_type_id:
                    raise ValueError("缺少pollution_type_id字段")

                example = pollution_type_service.create_pollution_type_example(
                    customer_id, pollution_type_id, example_data
                )
                # 在服务层会话内获取完整的字典数据
                from core.database import get_db_session
                with get_db_session() as db:
                    fresh_example = db.query(PollutionTypeExample).filter(PollutionTypeExample.id == example.id).first()
                    created_examples.append(fresh_example.to_dict() if fresh_example else example.to_dict())
            except Exception as e:
                failed_items.append({
                    "index": i,
                    "data": example_data,
                    "error": str(e)
                })

        logger.info(f"用户 {current_user.username} 批量创建污染类型样例 (客户: {customer_id}, 成功: {len(created_examples)}, 失败: {len(failed_items)})")

        return {
            "code": 200,
            "message": "批量创建完成",
            "data": {
                "created_count": len(created_examples),
                "failed_count": len(failed_items),
                "created_examples": created_examples,
                "failed_items": failed_items
            },
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"批量创建污染类型样例异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 统计接口
@router.get("/statistics", response_model=dict)
async def get_pollution_type_statistics(
    customer_id: str = Query("default", description="客户标识"),
    current_user: User = Depends(get_current_active_user)
):
    """获取污染类型统计信息"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限访问指定客户数据")

        # 获取基本统计
        all_types = pollution_type_service.get_all_pollution_types(customer_id, active_only=False)
        active_types = pollution_type_service.get_all_pollution_types(customer_id, active_only=True)

        # 按层级统计
        level_stats = {}
        for ptype in all_types:
            level = ptype["level"]
            if level not in level_stats:
                level_stats[level] = {"total": 0, "active": 0}
            level_stats[level]["total"] += 1
            if ptype["is_active"]:
                level_stats[level]["active"] += 1

        # 获取样例统计
        total_examples = 0
        active_examples = 0
        type_with_examples = 0

        for ptype in active_types:
            examples = pollution_type_service.get_pollution_type_examples(customer_id, ptype["id"], active_only=False)
            if examples:
                type_with_examples += 1
                total_examples += len(examples)
                active_examples += len([ex for ex in examples if ex['is_active']])

        logger.info(f"用户 {current_user.username} 获取污染类型统计 (客户: {customer_id})")

        return {
            "code": 200,
            "message": "获取统计成功",
            "data": {
                "types_total": len(all_types),
                "types_active": len(active_types),
                "types_inactive": len(all_types) - len(active_types),
                "examples_total": total_examples,
                "examples_active": active_examples,
                "examples_inactive": total_examples - active_examples,
                "types_with_examples": type_with_examples,
                "level_distribution": level_stats
            },
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"获取污染类型统计异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")




# ========== 批量操作API端点 ==========

class BatchDeleteRequest(BaseModel):
    """批量删除请求"""
    ids: List[int] = Field(..., description="要删除的污染类型ID列表")
    customer_id: str = Field("default", description="客户标识")

class BatchToggleRequest(BaseModel):
    """批量激活/停用请求"""
    ids: List[int] = Field(..., description="要操作的污染类型ID列表")
    is_active: bool = Field(..., description="激活状态")
    customer_id: str = Field("default", description="客户标识")

@router.post("/batch-delete", response_model=dict)
async def batch_delete_pollution_types(
    request: BatchDeleteRequest,
    current_user: User = Depends(get_current_active_user)
):
    """批量删除污染类型"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and request.customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        if not request.ids:
            raise HTTPException(status_code=400, detail="请提供要删除的ID列表")

        if len(request.ids) > 100:
            raise HTTPException(status_code=400, detail="单次批量删除不能超过100个")

        # 执行批量删除
        result = pollution_type_service.batch_delete_pollution_types(
            request.customer_id,
            request.ids
        )

        logger.info(f"用户 {current_user.username} 批量删除污染类型 (客户: {request.customer_id}, 成功: {result.get('deleted_count', 0)}, 失败: {result.get('failed_count', 0)})")

        return {
            "code": 200,
            "message": "批量删除完成",
            "data": result,
            "timestamp": time.time()
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"批量删除污染类型异常: {str(e)}")
        import traceback
        logger.error(f"批量删除污染类型异常堆栈: {traceback.format_exc()}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.post("/batch-toggle", response_model=dict)
async def batch_toggle_pollution_types(
    request: BatchToggleRequest,
    current_user: User = Depends(get_current_active_user)
):
    """批量激活/停用污染类型"""
    try:
        # 检查用户权限
        if not current_user.is_superuser and request.customer_id != "default":
            raise HTTPException(status_code=403, detail="无权限操作指定客户数据")

        if not request.ids:
            raise HTTPException(status_code=400, detail="请提供要操作的ID列表")

        if len(request.ids) > 100:
            raise HTTPException(status_code=400, detail="单次批量操作不能超过100个")

        # 执行批量状态切换
        result = pollution_type_service.batch_toggle_pollution_types(
            request.customer_id,
            request.ids,
            request.is_active
        )

        action = "激活" if request.is_active else "停用"
        logger.info(f"用户 {current_user.username} 批量{action}污染类型 (客户: {request.customer_id}, 成功: {result.get('updated_count', 0)}, 失败: {result.get('failed_count', 0)})")

        return {
            "code": 200,
            "message": f"批量{action}完成",
            "data": result,
            "timestamp": time.time()
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"批量切换污染类型状态异常: {str(e)}")
        import traceback
        logger.error(f"批量切换污染类型状态异常堆栈: {traceback.format_exc()}")
        raise HTTPException(status_code=500, detail="服务器内部错误")